<template>
  <main class="wss-container">
    <div class="documentary-box">
      <NewCard title="跟单" :border="false" :isright="true">
        <template slot="right">
          <ComForm
            v-if="isRolesShow()"
            @EventOnsubmit="tableFiltle"
            @EventReset="reset"
            :list="comForm">
          </ComForm>
        </template>

        <el-table
          :data="documentaryList"
          style="width: 100%"
          highlight-current-row
          v-if="isRolesShow()"
        >
          <el-table-column label="" width="35">
            <template slot-scope="scope">
              <svg-icon icon-class="jxz_icon" v-if="scope.row.status=='3'"/>
              <svg-icon icon-class="ywc_icon" v-else-if="scope.row.status=='0'"/>
            </template>
          </el-table-column>
          <el-table-column label="订单号" width="180">
            <template slot-scope="scope">
              <p>{{ scope.row.orderNo }}</p>
            </template>
          </el-table-column>
          <el-table-column label="专家" width="120">
            <template slot-scope="scope">
              <!-- 2咨询 3项目 -->
              <!-- 项目专家只能换该跟单下负责的同类型同城市专家 -->
              <div class="select-box" v-hasPermi="['financial:order:updateOrderExpert']" v-if="scope.row.type == '6'">
                <p>{{ scope.row.expertName }} <i class="el-icon-caret-bottom" v-if="scope.row.status != '0'"></i></p>
                <!-- 已完成的就不能改专家了 -->
                <el-select v-model="scope.row.expertId" placeholder="请选择" @change="updateProjectExpert(scope.row)" @visible-change="projectVisible(scope.row)" v-if="scope.row.status != '0'">
                  <el-option
                    v-for="item in selectconsultExperts"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <!-- 项目专家只能换该跟单下负责的同类型同城市专家 end-->

              <!-- 咨询专家只能分配相同擅长领域和相同等级的专家 -->
              <div class="select-box" v-hasPermi="['financial:order:updateOrderExpert']" v-else>
                <p>{{ scope.row.expertName }} <i class="el-icon-caret-bottom" v-if="scope.row.status != '0'"></i></p>
                <!-- 已完成的就不能改专家了 -->
                <el-select v-model="scope.row.expertId" placeholder="请选择" @change="updateExpert(scope.row)" @visible-change="visibleChange(scope.row)" v-if="scope.row.status != '0'">
                  <el-option
                    v-for="item in selectconsultExperts"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <!-- 咨询专家只能分配相同擅长领域和相同等级的专家 end -->
            </template>
          </el-table-column>
          <el-table-column label="订单类型" width="100">
            <template slot-scope="scope">
              <p>{{ scope.row.type == "6" ? "项目" : "咨询" }}</p>
            </template>
          </el-table-column>
          <el-table-column label="订单名称">
            <template slot-scope="scope">
                <el-popover placement="top-start" width="300" trigger="hover" :content="`${scope.row.nickname}-${scope.row.title}`">
                  <p slot="reference">{{scope.row.nickname}}-{{ scope.row.title }}</p>
                </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="订单金额" width="100" align="right">
            <template slot-scope="scope">
              <p>{{ scope.row.amount | sumFilters }}</p>
            </template>
          </el-table-column>
          <el-table-column label="分成金额" width="100" align="right">
            <template slot-scope="scope">
              <p>{{ scope.row.expertCommission | sumFilters }}</p>
            </template>
          </el-table-column>
          <el-table-column label="计划时间" width="220">
            <template slot-scope="scope">
              <p v-if="scope.row.type == '6'">
                <template>{{
                  scope.row.createdTime.slice(0, 10).replace(/-/g, "")
                }}</template
                >-
                <template>{{
                  scope.row.endTime.slice(0, 10).replace(/-/g, "")
                }}</template>
                <template v-if="scope.row.overdue"
                  >(逾期{{ scope.row.overdue }}天)</template
                >
              </p>
              <p v-else>--</p>
            </template>
          </el-table-column>
          <!-- <el-table-column label="订单状态" width="80">
            <template slot-scope="scope">
              <p class="islight" @click="viewDetail(scope.row)">
                {{ getOrderState(scope.row) }}
              </p>
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="50">
            <template slot-scope="scope">
              <el-button type="text" @click="overOrder(scope.row)" v-if="scope.row.status != '0'">结案</el-button>
              <p class="islight" v-else>--</p>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageing.pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageing.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageing.total"
          >
          </el-pagination>
        </div>

        <Comdrawer
          size="60%"
          title="订单详情"
          :drawer="detailState"
          @eventColse="eventColse"
        >
          <template #title>
            <p class="drawer-title">{{ getOrderState(nowOrderInfo) }}</p>
          </template>
          <!-- 项目详情 -->
          <Project
            :orderInfo="nowOrderInfo"
            v-if="nowOrderInfo.type == '6'"
          ></Project>
          <!-- 咨询详情 -->
          <OrderDetails :orderInfo="nowOrderInfo" v-else></OrderDetails>
        </Comdrawer>
      </NewCard>
    </div>
  </main>
</template>

<script>
import NewCard from "@/wss/components/newCard.vue";
import ComForm from "@/wss/components/comForm.vue";
import Comdrawer from "@/wss/components/Comdrawer.vue";
import OrderDetails from "./orderDetails.vue";
import Project from "./project/project.vue";
import debounce from "lodash/debounce";

import { getDocumentaryListOrderApi,getExpertListApi,overClosOrderApi,overProjectFinishApi,updateOrderExpertApi,getProjectRuleSelectExpertByCityApi } from "@/wss/newApi_3-24/work/documentary.js";
export default {
  components: { NewCard, ComForm, Comdrawer, OrderDetails, Project },
  data() {
    return {
      // 表单配置
      comForm: {
        modes: [
          {
            mode: "orderNo",
            formType: "input",
            placeholder: "订单号",
          },
          {
            mode: "title",
            formType: "input",
            placeholder: "订单名称",
          },
          {
            mode: "expertId",
            formType: "select",
            placeholder: "专家",
            select: [],
          },
          {
            mode: "status",
            formType: "select",
            placeholder: "订单状态",
            // 订单状态 -1已关闭 0已完成 1未支付 2已支付 3进行中
            select: [
              {
                label: "已关闭",
                value: "-1",
              },
              {
                label: "已完成",
                value: "0",
              },
              {
                label: "未支付",
                value: "1",
              },
              {
                label: "已支付",
                value: "2",
              },
              {
                label: "进行中",
                value: "3",
              },
            ],
          },
        ],
      },
      //分页参数
      pageing: { pageNum: 1, pageSize: 10, total: 0, sort: "DESC", order: "created_time", },
      expertPage: { pageNum: 1, pageSize: 50, total: 0, status: 1 },//专家 status=1审核成功的专家
      documentaryList: [], // 跟单列表

      detailState: false, //查看详情状态
      nowOrderInfo: {}, // 当前点击的订单信息
      filtrateData:{},//筛选表单

      consultExperts: [],//咨询专家的列表
      selectconsultExperts: [],//当前被选择的所有咨询专家 和订单一样的擅长领域和等级
      projectExperts: [],//项目专家的列表
    };
  },
  async mounted() {
    await this.getDocumentaryListOrder(); // 跟单对应的订单
    this.getExpertList() //获取专家列表
    // 拿到所有专家的名字
    /*let arr = [];
    this.documentaryList.forEach((item) => {
      let eArr = item.expertName.split(",");
      arr = [...arr, ...eArr];
    });
    let setArr = [...new Set(arr)] //去重
    // 转成label\value
    let newArr = [];
    setArr.forEach((item, i) => {
      newArr.push({
        label: item,
        value: item,
      });
    });
    // 当前表格跟单的全部专家,给到筛选
    this.comForm.modes[2].select = newArr;*/
  },
  methods: {
    // 分页器
    handleSizeChange(val) {
      this.pageing.pageSize = val;
      this.getDocumentaryListOrder(); // 跟单对应的订单
    },
    handleCurrentChange(val) {
      this.pageing.pageNum = val;
      this.getDocumentaryListOrder(); // 跟单对应的订单
    },
    // 分页器 end

    // 判断当前项目列表是否展示 根据角色
    isRolesShow(){
      let roles = this.$store.state.user.roles
      if(roles.includes('admin') || roles.includes('gd')){
        return true
      }else{
        return false
      }
    },

    // 跟单对应的订单
    async getDocumentaryListOrder() {
      // 合并跟单id 和其他
      let id = {
        followId: this.$store.state.user.userId, //获取跟单id
      };
      let pageing = this.pageing
      let idOrPage = Object.assign(id, pageing);
      let data = Object.assign(idOrPage, this.filtrateData);
      let result = await getDocumentaryListOrderApi(data);
      if (result.code == 200) {
        this.documentaryList = result.rows;
        this.pageing.total = result.total
      }
    },

    // 获取专家列表
    async getExpertList(){
      let pageing = this.expertPage
      let result = await getExpertListApi(pageing)
      if(result.code==200){
        // 转成label\value
        let newArr = [];
        result.rows.forEach(item=>{
          newArr.push({
            label: item.name,
            value: item.id,
          });
        })
        // 当前表格跟单的全部专家,给到筛选
        this.comForm.modes[2].select = newArr
        // 获取所有咨询专家 这里2咨询专家 3项目专家
        this.consultExperts = result.rows.filter(item=>{
          return item.type == '2'
        })
        // 获取所有项目专家 这里2咨询专家 3项目专家
        this.projectExperts = result.rows.filter(item=>{
          return item.type == '3'
        })
      } 
    },

    // 筛选表格数据 项目列表
    tableFiltle(arr) {
      let obj = {};
      arr.forEach((item) => {
        obj = Object.assign(obj, item);
      });
      this.filtrateData = obj
      this.getDocumentaryListOrder(); // 跟单对应的订单
    },

    // 重置按钮的回调
    reset() {
      this.filtrateData = {}
      this.getDocumentaryListOrder(); // 跟单对应的订单
    },

    // 获取订单的状态
    getOrderState(row) {
      // 订单状态 -1已关闭 0已完成 1未支付 2已支付 3进行中
      const stateMap = {
        "-1": "已关闭",
        0: "已完成",
        1: "未支付",
        2: "已支付",
        3: "进行中",
      };
      return stateMap[row.status];
    },

    //关闭抽屉
    eventColse() {
      this.detailState = false; //显示详情
    },

    // 点击查看订单详情
    viewDetail(row) {
      this.detailState = true; //显示详情
      this.nowOrderInfo = row; //订单详情
    },

    // 点击结束订单的按钮
    overOrder: debounce(async function(row){
      if(row.type == '5'){
        await this.overClosOrder(row) //咨询订单结束订单的接口
        this.getDocumentaryListOrder(); // 重新获取跟单对应的订单
      }else{
        await this.overProjectFinish(row.id) //项目订单结束订单的接口
        this.getDocumentaryListOrder(); // 重新获取跟单对应的订单
      }
    },1000),

    // 咨询订单点击结束订单的接口 (结束咨询订单的接口)
    async overClosOrder(data){
      let result = await overClosOrderApi(data)
      if(result.code==200) {
        this.$message({message: '操作成功',type: 'success'});
      }
    },

    // 项目订单点击结束订单的接口 (结束项目订单的接口)
    async overProjectFinish(orderId){
      let result = await overProjectFinishApi(orderId)
      if(result.code==200) {
        this.$message({message: '操作成功',type: 'success'});
      }
    },

    // -----------------------改咨询专家-----------------------
    // 点开咨询选择框 过滤出相同擅长领域和相同等级的咨询专家
    visibleChange(row){
      console.log(row);
      let remark = row.remark.split('：')
      let level = remark[2].split('；')[0]
      this.selectconsultExperts = this.consultExperts.filter(item=>{
        return item.consultType.includes(row.title) && item.levelName == level
      })
    },

    // 修改专家的选择框变化的时候
    async updateExpert(row){
      let expertId = row.expertId
      let id = row.id
      let typeNum = row.type
      await this.updateOrderExpert(id,expertId,typeNum)
      this.getDocumentaryListOrder(); // 重新获取跟单对应的订单
    },
    // -----------------------改咨询专家-----------------------end

    // ---------------改项目专家-----------------------
    // 点开项目选择框 
    projectVisible(row){
      // 要去发请求获取相同擅长领域和相同城市的项目专家
      this.getProjectRuleSelectExpertByCity(row.goodsId)
    },

    async getProjectRuleSelectExpertByCity(esId){
      let result = await getProjectRuleSelectExpertByCityApi(esId)
      if(result.code==200){
        this.selectconsultExperts = result.data
      }
    },

    // 修改项目专家的选择框变化的时候
    async updateProjectExpert(row){
      let expertId = row.expertId
      let id = row.id
      let typeNum = row.type
      await this.updateOrderExpert(id,expertId,typeNum)
      this.getDocumentaryListOrder(); // 重新获取跟单对应的订单
    },
    // ---------------改项目专家-----------------------end

    // 重新分配专家
    async updateOrderExpert(id,expertId,typeNum){
      let type = ''
      if(typeNum=='5'){
        type = '2' //咨询专家
      }else{
        type = '3' //项目专家
      }
      let result = await updateOrderExpertApi(id,expertId,type)
      if(result.code==200){
        this.$message({message: '分配成功',type: 'success'});
      }
    },
  },
};
</script>

<style scoped>
h3,
h4,
p,
ul{
  margin: 0;
  padding: 0;
}

.documentary-box {
  height: 100%;
}
.documentary-box .el-row {
  height: 100%;
  margin-bottom: 0;
}
.documentary-box .el-col,
.documentary-box .el-card {
  height: 100%;
}
.documentary-box .el-card {
  position: relative;
}
.documentary-box >>> .el-card__body {
  height: 100%;
}
.documentary-box >>> .el-card__body > div {
  height: 92%;
  overflow-y: auto;
}
.documentary-box >>> .el-card__body > div::-webkit-scrollbar {
  width: 0;
}

/* 分页器 */
::v-deep .documentary-box .pagination {
  text-align: center;
  margin-top: 30px;
}

/* 表单样式 */
::v-deep .documentary-box .el-form .el-input--medium {
  width: 140px !important;
}
::v-deep .documentary-box .el-form .el-form-item .el-button--default {
  /* display: none; */
}

/* 表格样式 */
::v-deep .el-table .el-table__header-wrapper th {
  background-color: #fff;
}
::v-deep .el-table th.is-leaf {
  border-top: 1px solid #efefef;
  border-bottom: 1px solid #efefef;
}
::v-deep .el-table th > .cell {
  font-size: 12px;
  color: #909aaa;
}
::v-deep .el-table .cell,
::v-deep .el-table .cell p {
  margin: 0;
  font-size: 14px;
  color: #2e3f5e;
}
::v-deep .el-table .cell p{
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
}
::v-deep .el-table .cell .el-button {
  color: #f87a23;
}
::v-deep .el-table .cell .el-table__expand-icon i::before {
  content: "\E791";
}
::v-deep .el-table td {
  /* border-bottom: 0; */
}
::v-deep .el-table td .islight {
  color: #f87a23;
  cursor: pointer;
}
::v-deep .el-table .el-table__expanded-cell[class*="cell"] {
  padding: 0;
}
::v-deep .el-table__expanded-cell .el-table::before {
  height: 0;
}
::v-deep .el-table__expanded-cell .el-table th.is-leaf {
  border-top: 0;
}
::v-deep .el-table__expanded-cell .el-table td {
  border-bottom: 0;
}
.assistant-box span:last-child > i {
  display: none;
}

.el-table .select-box{
  position: relative;
}
.el-table .select-box .el-select{
  position: absolute;
  opacity: 0;
  top: -5px;
}

::v-deep .el-table .el-select .el-input__inner{
  padding-left: 10px;
  padding-right: 10px
}
::v-deep .el-table .el-select .el-input__suffix{
  display: none;
}

/* 表格样式 end */

/* 订单详情 */
.drawer-title {
  font-size: 12px;
  font-weight: 400;
  color: #99a2b1;
}
.drawerMain {
  padding: 0 30px;
}
.drawerMain h4 {
  padding: 10px 15px;
  background-color: #f4f5f8;
  font-size: 12px;
  font-weight: 400;
  color: #2e3f5e;
}

.drawerMain h3 {
  font-size: 16px;
  font-weight: 600;
  color: #2e3f5e;
  margin-bottom: 20px;
  margin-top: 30px;
}
.drawerMain ul {
  border-bottom: 1px solid #efefef;
}
.drawerMain li {
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;
  margin-bottom: 15px;
}
.drawerMain li > span {
  display: block;
  width: 15%;
  color: #999999;
}
.drawerMain li > p {
  font-size: 14px;
  font-weight: 400;
  color: #222;
}
.drawerMain li > p > a {
  display: block;
  color: #f87a23;
  margin-bottom: 15px;
}
/* 订单详情 end*/

@media (max-width: 1180px) {
  .el-table .cell p{
    overflow:hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow:ellipsis;
  }
}
</style>
